package common.commands;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;

import math.Relation;

import common.Relations;

import ui.WindowManager;
import ui.gui.documents.AbstractDocument;
import ui.gui.documents.toolbox.Workspace;

public class CommandSaveWorkspace implements ICommand {

	@Override
	public String getName() {
		
		return "save-workspace";
	}

	@Override
	public String getSynopsis() {
		
		return "save-workspace";
	}

	@Override
	public CommandValue run(String arg) {	
		StringBuilder listCommands = new StringBuilder();
		for (AbstractDocument document : Workspace.getInstance().getDocuments()) {
			listCommands.append("load " + document.getFile().getAbsolutePath() + "\n");
		}
		for (Relation relation : Relations.getRelations()) {
			listCommands.append("select-model " + relation.getModel().getAst().getFileName() + "\n");
			listCommands.append(relation.toString() + "\n");
		}
		try
    	{
	        Writer output = new BufferedWriter(new FileWriter(arg));
	        output.write(listCommands.toString());
	        output.close();
    	}
    	catch (Exception ex) {
    		System.out.println("Unable to save workspace to file " + arg);
    		return CommandValue.KO;
    	}
    	System.out.println("Workspace [" + arg + "] loaded");
		return CommandValue.OK;
	}

	@Override
	public String help() {
		
		return "This command save current CLAC workspace";
	}

}
